<template>
  <el-config-provider :locale="zhCn">
    <div class="human-intervention">
      <!-- 筛选条件区域 -->
      <filter-form v-model="filterForm" :form-items="formItems" @search="handleSearch" @reset="resetFilter" @update:modelValue="handleFilterChange" />

      <!-- 操作按钮区域 -->
      <div class="operation-section">
        <el-button type="success" @click="handleCreateRule">新增规则</el-button>
      </div>

      <!-- 列表展示区域 -->
      <div class="table-section">
        <el-table :data="ruleList" border style="width: 100%" v-loading="loading" class="custom-table">
          <el-table-column type="index" label="序号" width="60" />
          <el-table-column prop="name" label="规则名称" min-width="150" />
          <el-table-column label="关键词" min-width="200">
            <template #default="scope">
              <div class="keyword-list">
                <el-tag v-for="keyword in scope.row.umWechatKeywords" :key="keyword.id" class="keyword-tag" size="small">
                  {{ keyword.keyword }}
                </el-tag>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="type" label="介入场景" width="120">
            <template #default="scope">
              {{ scope.row.type === '1' ? '客户提问' : 'AI回答' }}
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="100">
            <template #default="scope">
              <el-tooltip :content="scope.row.status === '1' ? '点击禁用' : '点击启用'" placement="top" effect="dark">
                <el-switch v-model="scope.row.status" :active-value="'1'" :inactive-value="'2'" @change="handleStatusChange(scope.row)" />
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column prop="createByStr" label="创建人" width="120" />
          <el-table-column prop="createTime" label="创建时间" width="180" />
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="scope">
              <el-button type="primary" link @click="handleEdit(scope.row)">编辑</el-button>
              <el-button type="danger" link @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :total="total" @pagination="handlePagination" />

      <!-- 新增/编辑规则对话框 -->
      <el-dialog v-model="ruleDialogVisible" :title="dialogType === 'create' ? '新增规则' : '编辑规则'" width="500px" destroy-on-close class="rule-dialog">
        <el-form :model="ruleForm" label-width="100px" class="rule-form">
          <el-form-item label="规则名称" required>
            <el-input v-model="ruleForm.name" placeholder="请输入规则名称" />
          </el-form-item>
          <el-form-item label="介入场景" required>
            <el-select v-model="ruleForm.type" placeholder="请选择介入场景">
              <el-option v-for="item in sceneOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="状态">
            <el-radio-group v-model="ruleForm.status">
              <el-radio label="1">启用</el-radio>
              <el-radio label="2">禁用</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="关键词" required>
            <div class="keyword-container">
              <div class="keyword-tags">
                <el-tag v-for="tag in keywordTags" :key="tag" closable :disable-transitions="false" @close="handleClose(tag)" class="keyword-tag">
                  {{ tag }}
                </el-tag>
                <el-input
                  v-if="inputVisible"
                  ref="InputRef"
                  v-model="inputValue"
                  class="keyword-input"
                  size="small"
                  @keyup.enter="handleInputConfirm"
                  @blur="handleInputConfirm"
                />
                <el-button v-else class="button-new-tag" size="small" @click="showInput"> + 添加关键词 </el-button>
              </div>
            </div>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="ruleDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitRule">确定</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </el-config-provider>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';
import { getHumanInterventionList, addHumanIntervention, updateHumanIntervention, deleteHumanIntervention } from '@/api/userRate/humanIntervention';
import zhCn from 'element-plus/es/locale/lang/zh-cn';
import FilterForm from '@/components/FilterForm/index.vue';
import Pagination from '@/components/Pagination/index.vue';
import type { FormItem } from '@/components/FilterForm/index.vue';

interface ApiResponse<T = any> {
  code: number;
  msg: string;
  data: T;
}

interface Keyword {
  id: number;
  keyword: string;
  type: string;
  humanInterventionId: number;
}

interface Rule {
  id: number;
  name: string;
  status: string;
  createByStr: string;
  createTime: string;
  isDelete: string;
  umWechatKeywords: Keyword[];
  keywords: string | null;
  type: string | null;
}

interface RuleForm {
  id?: number;
  name: string;
  status: string;
  createByStr: string;
  type: string;
  keywords?: string;
}

interface CreateRuleParams {
  name: string;
  status: string;
  createByStr: string;
  keywords: string;
  type: string;
  wxId: string;
}

interface UpdateRuleParams {
  id: string;
  name: string;
  status: string;
  keywords: string;
  type: string;
  wxId: string;
}

interface ListParams {
  name?: string;
  type?: string;
  status?: string;
  keyword?: string;
  current?: number;
  size?: number;
}

// 筛选表单
const filterForm = reactive({
  name: '',
  type: '',
  status: '',
  keyword: ''
});

// 表单项配置
const formItems = computed<FormItem[]>(() => [
  {
    label: '规则名称',
    prop: 'name',
    type: 'input',
    placeholder: '请输入规则名称'
  },
  {
    label: '介入场景',
    prop: 'type',
    type: 'select',
    placeholder: '请选择介入场景',
    options: sceneOptions
  },
  {
    label: '状态',
    prop: 'status',
    type: 'select',
    placeholder: '请选择状态',
    options: [
      { label: '启用', value: '1' },
      { label: '禁用', value: '2' }
    ]
  },
  {
    label: '关键词',
    prop: 'keyword',
    type: 'input',
    placeholder: '请输入关键词'
  }
]);

// 分页相关
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const ruleList = ref<Rule[]>([]);

// 获取 wxId
const wxId = ref(localStorage.getItem('msgprofile') ? JSON.parse(localStorage.getItem('msgprofile')!).wx_id : '');

// 加载状态
const loading = ref(false);

// 对话框相关
const ruleDialogVisible = ref(false);
const dialogType = ref<'create' | 'edit'>('create');
const ruleForm = reactive<RuleForm>({
  name: '',
  status: '1',
  createByStr: '',
  type: '1'
});

// 场景选项
const sceneOptions = [
  { label: '客户提问', value: '1' },
  { label: 'AI回答', value: '2' }
];

// 关键词标签相关
const inputValue = ref('');
const inputVisible = ref(false);
const InputRef = ref();
const keywordTags = ref<string[]>([]);

// 获取 userInfo
const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
const account = userInfo.username || '';

// 查询方法
const handleSearch = async (formData?: Record<string, any>) => {
  loading.value = true;
  try {
    // 使用传入的表单数据或当前的表单数据
    const searchData = formData || filterForm;
    const params: ListParams = {
      name: searchData.name || undefined,
      type: searchData.type || undefined,
      status: searchData.status || undefined,
      keyword: searchData.keyword || undefined,
      current: currentPage.value,
      size: pageSize.value
    };

    // 移除所有 undefined 的参数
    Object.keys(params).forEach((key) => {
      if (params[key as keyof ListParams] === undefined) {
        delete params[key as keyof ListParams];
      }
    });

    const res = (await getHumanInterventionList(params)) as unknown as ApiResponse<{
      records: Rule[];
      total: number;
      size: number;
      current: number;
    }>;
    if (res.code === 200) {
      ruleList.value = res.data.records;
      total.value = res.data.total;
    } else {
      ElMessage.error(res.msg || '获取数据失败');
    }
  } catch (error) {
    console.error('搜索失败：', error);
    ElMessage.error('获取数据失败');
  } finally {
    loading.value = false;
  }
};

// 重置筛选
const resetFilter = () => {
  filterForm.name = '';
  filterForm.type = '';
  filterForm.status = '';
  filterForm.keyword = '';
  currentPage.value = 1;
  pageSize.value = 10;
  handleSearch();
};

// 分页方法
const handlePagination = ({ pageNum, pageSize: size }: { pageNum: number; pageSize: number }) => {
  currentPage.value = pageNum;
  pageSize.value = size;
  handleSearch();
};

// 初始化数据
const initData = async () => {
  loading.value = true;
  try {
    const params: ListParams = {
      current: currentPage.value,
      size: pageSize.value
    };
    const res = (await getHumanInterventionList(params)) as unknown as ApiResponse<{
      records: Rule[];
      total: number;
      size: number;
      current: number;
    }>;
    if (res.code === 200) {
      ruleList.value = res.data.records;
      total.value = res.data.total;
    } else {
      ElMessage.error(res.msg || '获取数据失败');
    }
  } catch (error) {
    console.error('初始化数据失败：', error);
    ElMessage.error('获取数据失败');
  } finally {
    loading.value = false;
  }
};

// 显示输入框
const showInput = () => {
  inputVisible.value = true;
  nextTick(() => {
    InputRef.value?.input?.focus();
  });
};

// 处理输入确认
const handleInputConfirm = () => {
  if (inputValue.value) {
    if (!keywordTags.value.includes(inputValue.value)) {
      keywordTags.value.push(inputValue.value);
    }
  }
  inputVisible.value = false;
  inputValue.value = '';
};

// 处理标签关闭
const handleClose = (tag: string) => {
  keywordTags.value.splice(keywordTags.value.indexOf(tag), 1);
};

// 新增规则
const handleCreateRule = () => {
  dialogType.value = 'create';
  ruleForm.name = '';
  ruleForm.status = '1';
  ruleForm.keywords = '';
  ruleForm.createByStr = '';
  ruleForm.type = '1';
  keywordTags.value = [];
  ruleDialogVisible.value = true;
};

// 编辑规则
const handleEdit = (rule: Rule) => {
  dialogType.value = 'edit';
  const keywords = rule.umWechatKeywords?.map((k) => k.keyword).join(',') || '';
  Object.assign(ruleForm, {
    id: rule.id,
    name: rule.name,
    status: rule.status,
    createByStr: rule.createByStr,
    type: rule.type || '1',
    keywords
  });
  keywordTags.value = rule.umWechatKeywords?.map((k) => k.keyword) || [];
  ruleDialogVisible.value = true;
};

// 删除规则
const handleDelete = async (rule: Rule) => {
  if (!rule.id) return;

  try {
    await ElMessageBox.confirm('确定要删除该规则吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    const res = (await deleteHumanIntervention(rule.id)) as unknown as ApiResponse;
    if (res.code === 200) {
      ElMessage.success('删除成功');
      handleSearch();
    } else {
      ElMessage.error(res.msg || '删除失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败');
    }
  }
};

// 状态变更
const handleStatusChange = async (rule: Rule) => {
  if (!rule.id) return;

  try {
    const res = (await updateHumanIntervention({
      id: rule.id.toString(),
      name: rule.name,
      status: rule.status,
      keywords: rule.umWechatKeywords?.map((k) => k.keyword).join(',') || '',
      type: rule.type || '1',
      account
    })) as unknown as ApiResponse;

    if (res.code === 200) {
      ElMessage.success(`规则${rule.status === '1' ? '启用' : '禁用'}成功`);
    } else {
      ElMessage.error(res.msg || '操作失败');
      // 恢复状态
      rule.status = rule.status === '1' ? '2' : '1';
    }
  } catch (error) {
    ElMessage.error('操作失败');
    // 恢复状态
    rule.status = rule.status === '1' ? '2' : '1';
  }
};

// 提交规则
const submitRule = async () => {
  if (!ruleForm.name) {
    ElMessage.warning('请填写规则名称');
    return;
  }

  if (keywordTags.value.length === 0) {
    ElMessage.warning('请添加至少一个关键词');
    return;
  }

  if (!ruleForm.type) {
    ElMessage.warning('请选择介入场景');
    return;
  }

  try {
    if (dialogType.value === 'create') {
      const params: CreateRuleParams = {
        name: ruleForm.name,
        status: ruleForm.status,
        keywords: keywordTags.value.join(','),
        createByStr: ruleForm.createByStr || '',
        type: ruleForm.type,
        wxId: wxId.value,
        account
      };
      const res = (await addHumanIntervention(params)) as unknown as ApiResponse;
      if (res.code === 200) {
        ElMessage.success('创建成功');
        ruleDialogVisible.value = false;
        handleSearch();
      } else {
        ElMessage.error(res.msg || '操作失败');
      }
    } else {
      const params: UpdateRuleParams = {
        id: ruleForm.id?.toString() || '',
        name: ruleForm.name,
        status: ruleForm.status,
        keywords: keywordTags.value.join(','),
        type: ruleForm.type,
        wxId: wxId.value,
        account
      };
      const res = (await updateHumanIntervention(params)) as unknown as ApiResponse;
      if (res.code === 200) {
        ElMessage.success('更新成功');
        ruleDialogVisible.value = false;
        handleSearch();
      } else {
        ElMessage.error(res.msg || '操作失败');
      }
    }
  } catch (error) {
    ElMessage.error('操作失败');
  }
};

// 处理筛选条件变化
const handleFilterChange = (val: any) => {
  filterForm.name = val.name || '';
  filterForm.type = val.type || '';
  filterForm.status = val.status || '';
  filterForm.keyword = val.keyword || '';
};

// 初始化
onMounted(() => {
  initData();
});
</script>

<style lang="scss" scoped>
.human-intervention {
  padding: 20px;
  min-height: calc(100vh - 40px);

  .operation-section {
    margin-bottom: 20px;
    display: flex;
    gap: 12px;
  }

  .table-section {
    background-color: #fff;
    border-radius: 8px;
    padding: 20px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);

    .custom-table {
      :deep(.el-table__header) {
        th {
          background-color: #f5f7fa;
          color: #606266;
          font-weight: 600;
        }
      }

      :deep(.el-table__row) {
        &:hover {
          td {
            background-color: #f5f7fa;
          }
        }
      }
    }

    .notification-types {
      display: flex;
      flex-wrap: wrap;
      gap: 8px;

      .notification-tag {
        margin: 0;
      }
    }
  }

  .pagination-section {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
    padding: 16px 0;

    .custom-pagination {
      :deep(.el-pagination__total) {
        margin-right: 16px;
      }

      :deep(.el-pagination__sizes) {
        margin-right: 16px;
      }
    }
  }
}

.rule-dialog {
  :deep(.el-dialog__body) {
    padding: 20px 30px;
  }

  .rule-form {
    .el-form-item {
      margin-bottom: 22px;
    }

    .notification-select {
      width: 100%;
    }
  }
}

:deep(.el-button) {
  display: inline-flex;
  align-items: center;
  gap: 4px;
}

.keyword-container {
  width: 100%;
}

.keyword-tags {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 8px;
  min-height: 32px;
}

.keyword-tag {
  margin: 0;
}

.keyword-input {
  width: 90px;
  margin: 0;
  vertical-align: middle;
}

.button-new-tag {
  margin: 0;
}

.keyword-list {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
  padding: 4px 0;

  .keyword-tag {
    margin: 0;
  }
}
</style>
